package com.ztc.service;

import javax.sound.midi.*;
import javax.swing.*;
import java.awt.*;

/**
 * Created by ztc on 15-11-23.
 */
public class Sound {
    public static void main(String[] args){
        new Sound().play();
    }
    public void play(){
        try {
            MyPanel m=new MyPanel();
            JFrame f=new JFrame();
            f.add(m);
            f.setSize(300,300);
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Sequencer player= MidiSystem.getSequencer();
            player.open();
            int[] eventsIwant={126};
            player.addControllerEventListener(m,eventsIwant);

            Sequence seq=new Sequence(Sequence.PPQ,4);

            Track track=seq.createTrack();

            for(int i=40;i<90;i+=4){
                track.add(makeEvent(144,5,i,100,i));
                track.add(makeEvent(176,1,126,0,i));
                track.add(makeEvent(128,5,i,100,i+2));
            }
            player.setSequence(seq);
            player.start();
            System.out.println("end");
        } catch (MidiUnavailableException e) {
            e.printStackTrace();
        } catch (InvalidMidiDataException e) {
            e.printStackTrace();
        }
    }
    public MidiEvent makeEvent(int comd,int chan,int one,int two,int tick){
        MidiEvent event=null;
        try {
            ShortMessage b=new ShortMessage();
            b.setMessage(comd, chan, one, two);
            event=new MidiEvent(b,tick);
        } catch (InvalidMidiDataException e) {
            e.printStackTrace();
        }
        return event;
    }

    class MyPanel extends JPanel implements ControllerEventListener{
        @Override
        public void controlChange(ShortMessage event) {
            repaint();
        }

        public void paintComponent(Graphics g){
            Graphics2D g2=(Graphics2D)g;
            int r=(int)(Math.random()*250);
            int gr=(int)(Math.random()*250);
            int b=(int)(Math.random()*250);

            g.setColor(new Color(r,gr,b));

            int ht=(int)((Math.random()*120)+10);
            int we=(int)((Math.random()*120)+10);
            int x=(int)((Math.random()*40)+10);
            int y=(int)((Math.random()*40)+10);
            g.fillRect(x,y,ht,we);
        }
    }
}
